package com.kamistoat.meimeistore.commonredis.configure.properties;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.ByteBufInputStream;
import io.netty.buffer.ByteBufOutputStream;
import org.redisson.client.codec.BaseCodec;
import org.redisson.client.protocol.Decoder;
import org.redisson.client.protocol.Encoder;

/**
 * 自己实现的序列化编解码类，用于规定Redisson的序列化机制
 */
public class FastJson2JsonCodec extends BaseCodec {
    /**
     * Returns object decoder used for any objects stored Redis structure except HMAP
     *
     * @return decoder
     */
    @Override
    public Decoder<Object> getValueDecoder() {
        return decoder;
    }

    /**
     * Returns object encoder used for any objects stored Redis structure except HMAP
     *
     * @return encoder
     */
    @Override
    public Encoder getValueEncoder() {
        return encoder;
    }

    /**
     * 自定义的Encoder
     */
    private final Encoder encoder = in -> {
        ByteBuf out = ByteBufAllocator.DEFAULT.buffer();
        try {
            ByteBufOutputStream os = new ByteBufOutputStream(out);
            // 使用FastJSON2做序列化机制且在序列化时记录元类信息以方便反序列化
            JSON.writeTo(os, in, JSONWriter.Feature.WriteClassName);
            return os.buffer();
        } catch (Exception e) {
            out.release();
            throw e;
        }
    };

    private final Decoder<Object> decoder = (buf, state) ->
            JSON.parseObject(new ByteBufInputStream(buf), Object.class);
}
